package com.lss.loginregister.viewmodel;

import android.text.TextUtils;
import android.util.Log;

import androidx.databinding.ObservableField;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.lss.loginregister.entity.Person;

public class DataTransmitViewModel extends ViewModel {
    private static final String TAG = "DataTransmitViewModel";
    public ObservableField<String> ageError = new ObservableField<>();
    public ObservableField<String> nameError = new ObservableField<>();

    public void onAgeFocusChange(boolean hasFocus, String ageText) {
        // 当失去焦点时进行验证
        if (!hasFocus) {
            validateAge(ageText);
        }
    }

    public void onNameFocusChange(boolean hasFocus, String nameText) {
        // 当失去焦点时进行验证
        if (!hasFocus) {
            validateName(nameText);
        }
    }

    public void validateName(String nameText) {
        if (TextUtils.isEmpty(nameText)) {
            nameError.set("姓名不能为空");
        } else {
            nameError.set(null);
        }
    }

    // 验证年龄
    public void validateAge(String ageText) {
        if (TextUtils.isEmpty(ageText)) {
            ageError.set("年龄不能为空");
        } else {
            try {
                int age = Integer.parseInt(ageText);
                if (age <= 0) {
                    ageError.set("年龄必须大于0");
                } else {
                    ageError.set(null);
                }
            } catch (NumberFormatException e) {
                ageError.set("请输入有效数字");
            }
        }
    }

    // 提交状态
    private MutableLiveData<Boolean> submitSuccess = new MutableLiveData<>();

    // 获取提交状态
    public LiveData<Boolean> getSubmitSuccess() {
        return submitSuccess;
    }

    // 提交方法
    public void onSubmit(Person person) {

        // 验证数据
        if (TextUtils.isEmpty(person.getName())) {
            // 显示姓名错误
            return;
        }

        if (ageError.get() != null) {
            // 年龄错误已显示
            return;
        }
        try {
            // 将字符串年龄转换为整数
            int age = person.getAge();
            person.setAge(age);
            // 执行提交逻辑
            submitPersonData(person);

            // 通知UI提交成功
            submitSuccess.setValue(true);
        } catch (NumberFormatException e) {
            ageError.set("年龄格式错误");
            submitSuccess.setValue(false);
        }
    }

    // 实际提交逻辑
    private void submitPersonData(Person person) {
        // repository.savePerson(person);

        // 模拟提交成功
        Log.d(TAG, "提交成功: " + person.toString());
    }
}